#!/usr/bin/env python3
"""
linuxptp MCP Server

面向 linuxptp 软件的命令行操作 MCP server，提供以下工具：
1. linuxptp_nsm_tool - 测试 nsm、hwstamp_ctl、phc2sys、phc_ctl 等命令的帮助和版本信息
   参数：无
   返回：统一的命令执行结果 JSON

2. linuxptp_pmc_tool - 测试 pmc 命令的各种选项
   参数：interface (str): 网络接口名称
   返回：统一的命令执行结果 JSON

3. linuxptp_ptp4l_basic_tool - 测试 ptp4l 的基本选项
   参数：interface (str): 网络接口名称, clock_type (str): 时钟类型选项
   返回：统一的命令执行结果 JSON

4. linuxptp_ptp4l_advanced_tool - 测试 ptp4l 的高级选项
   参数：interface (str): 网络接口名称, config_file (str): 配置文件路径
   返回：统一的命令执行结果 JSON

5. linuxptp_phc2sys_service_tool - 测试 phc2sys 服务状态
   参数：无
   返回：统一的命令执行结果 JSON

6. linuxptp_ptp4l_service_tool - 测试 ptp4l 服务状态
   参数：无
   返回：统一的命令执行结果 JSON

7. linuxptp_timemaster_tool - 测试 timemaster 命令的各种选项
   参数：config_file (str): 配置文件路径, monitor (bool): 是否启用监控模式
   返回：统一的命令执行结果 JSON

所有工具返回统一的 JSON 结构：
{
  "success": bool,
  "command": str,
  "exit_code": int,
  "stdout": str,
  "stderr": str
}
"""

import subprocess
import json
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("LinuxPTP MCP Server")

@mcp.tool()
def linuxptp_nsm_tool() -> dict:
    """
    测试 linuxptp 中 nsm、hwstamp_ctl、phc2sys、phc_ctl 等命令的帮助和版本信息
    
    返回：
        dict: 包含命令执行结果的统一 JSON 结构
    """
    commands = [
        "nsm -h",
        "nsm -v", 
        "hwstamp_ctl -h",
        "hwstamp_ctl -v",
        "phc2sys -h",
        "phc2sys -v",
        "phc_ctl -h",
        "phc_ctl -v"
    ]
    
    results = []
    for cmd in commands:
        try:
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
            results.append({
                "success": result.returncode == 0,
                "command": cmd,
                "exit_code": result.returncode,
                "stdout": result.stdout,
                "stderr": result.stderr
            })
        except Exception as e:
            results.append({
                "success": False,
                "command": cmd,
                "exit_code": -1,
                "stdout": "",
                "stderr": str(e)
            })
    
    return {"results": results}

@mcp.tool()
def linuxptp_pmc_tool(interface: str) -> dict:
    """
    测试 pmc 命令的各种选项
    
    参数：
        interface (str): 网络接口名称
        
    返回：
        dict: 包含命令执行结果的统一 JSON 结构
    """
    commands = [
        f"pmc -h",
        f"pmc -v",
        f"pmc -i {interface} -u -b 0 'GET CURRENT_DATA_SET'",
        f"pmc -i {interface} -u -b 1 -d 0 'GET TIME_STATUS_NP'",
        f"pmc -i {interface} -u -b 1 -d 0 'GET DOMAIN'",
        f"pmc -i {interface} -u -b 1 -d 0 'GET DOMAIN' -s /var/run/ptp4l",
        f"pmc -i {interface} -u -b 1 'GET PORT_DATA_SET' -t 0x0",
        f"pmc -i {interface} -u -b 1 'GET CLOCK_DESCRIPTION' -z",
        f"pmc -i {interface} -2 -b 1 'GET CLOCK_DESCRIPTION'",
        f"pmc -i {interface} -4 -b 1 'GET CLOCK_DESCRIPTION'",
        f"pmc -i {interface} -6 -b 1 'GET CLOCK_DESCRIPTION'"
    ]
    
    results = []
    for cmd in commands:
        try:
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
            results.append({
                "success": result.returncode == 0,
                "command": cmd,
                "exit_code": result.returncode,
                "stdout": result.stdout,
                "stderr": result.stderr
            })
        except Exception as e:
            results.append({
                "success": False,
                "command": cmd,
                "exit_code": -1,
                "stdout": "",
                "stderr": str(e)
            })
    
    return {"results": results}

@mcp.tool()
def linuxptp_ptp4l_basic_tool(interface: str, clock_type: str = "-A") -> dict:
    """
    测试 ptp4l 的基本选项
    
    参数：
        interface (str): 网络接口名称
        clock_type (str): 时钟类型选项，如 -A, -E, -P, -2, -4, -6
        
    返回：
        dict: 包含命令执行结果的统一 JSON 结构
    """
    cmd = f"timeout 20s ptp4l -i {interface} -m -S {clock_type}"
    
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=25)
        return {
            "success": result.returncode == 0,
            "command": cmd,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": cmd,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def linuxptp_ptp4l_advanced_tool(interface: str, config_file: str = "") -> dict:
    """
    测试 ptp4l 的高级选项
    
    参数：
        interface (str): 网络接口名称
        config_file (str): 配置文件路径，如果为空则使用默认选项
        
    返回：
        dict: 包含命令执行结果的统一 JSON 结构
    """
    commands = []
    
    # 基本命令测试
    commands.extend([
        "ptp4l -v",
        "ptp4l -h"
    ])
    
    # 配置文件测试
    if config_file:
        cmd = f"timeout 20s ptp4l -f {config_file} -i {interface}"
        commands.append(cmd)
    else:
        # 静默模式测试
        cmd = f"timeout 10s ptp4l -i {interface} -S -q"
        commands.append(cmd)
    
    results = []
    for cmd in commands:
        try:
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=25)
            results.append({
                "success": result.returncode == 0,
                "command": cmd,
                "exit_code": result.returncode,
                "stdout": result.stdout,
                "stderr": result.stderr
            })
        except Exception as e:
            results.append({
                "success": False,
                "command": cmd,
                "exit_code": -1,
                "stdout": "",
                "stderr": str(e)
            })
    
    return {"results": results}

@mcp.tool()
def linuxptp_phc2sys_service_tool() -> dict:
    """
    测试 phc2sys 服务状态
    
    返回：
        dict: 包含命令执行结果的统一 JSON 结构
    """
    commands = [
        "systemctl status phc2sys.service",
        "systemctl is-active phc2sys.service"
    ]
    
    results = []
    for cmd in commands:
        try:
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
            results.append({
                "success": result.returncode == 0,
                "command": cmd,
                "exit_code": result.returncode,
                "stdout": result.stdout,
                "stderr": result.stderr
            })
        except Exception as e:
            results.append({
                "success": False,
                "command": cmd,
                "exit_code": -1,
                "stdout": "",
                "stderr": str(e)
            })
    
    return {"results": results}

@mcp.tool()
def linuxptp_ptp4l_service_tool() -> dict:
    """
    测试 ptp4l 服务状态
    
    返回：
        dict: 包含命令执行结果的统一 JSON 结构
    """
    commands = [
        "systemctl status ptp4l.service",
        "systemctl is-active ptp4l.service"
    ]
    
    results = []
    for cmd in commands:
        try:
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
            results.append({
                "success": result.returncode == 0,
                "command": cmd,
                "exit_code": result.returncode,
                "stdout": result.stdout,
                "stderr": result.stderr
            })
        except Exception as e:
            results.append({
                "success": False,
                "command": cmd,
                "exit_code": -1,
                "stdout": "",
                "stderr": str(e)
            })
    
    return {"results": results}

@mcp.tool()
def linuxptp_timemaster_tool(config_file: str, monitor: bool = False) -> dict:
    """
    测试 timemaster 命令的各种选项
    
    参数：
        config_file (str): 配置文件路径
        monitor (bool): 是否启用监控模式
        
    返回：
        dict: 包含命令执行结果的统一 JSON 结构
    """
    commands = [
        "timemaster -h",
        "timemaster -v"
    ]
    
    # 根据参数构建不同的命令
    if monitor:
        cmd = f"timeout 10s timemaster -f {config_file} -m"
        commands.append(cmd)
    else:
        cmd = f"timemaster -f {config_file} -n"
        commands.append(cmd)
    
    results = []
    for cmd in commands:
        try:
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=15)
            results.append({
                "success": result.returncode == 0,
                "command": cmd,
                "exit_code": result.returncode,
                "stdout": result.stdout,
                "stderr": result.stderr
            })
        except Exception as e:
            results.append({
                "success": False,
                "command": cmd,
                "exit_code": -1,
                "stdout": "",
                "stderr": str(e)
            })
    
    return {"results": results}

if __name__ == "__main__":
    mcp.run()